<script setup>
import {onMounted, ref, watch} from 'vue'
import {useRoute} from 'vue-router'
import service from '@/api/request0.js'

const route = useRoute()
const products = ref([])

const fetchProducts = async () => {
  try {
    products.value = await service.get(`/product/category/${route.params.categoryId}`)

  } catch (error) {
    console.error('获取商品列表失败:', error.message)
    alert(`请求失败: ${error.message}`)
  }
}

watch(() => route.params.categoryId, () => {
  fetchProducts()
})

onMounted(fetchProducts)
</script>

<template>
  <div class="product-list">
    <h2 v-if="products.length">{{ products[0].categoryId }}</h2>
    <table>
      <thead>
      <tr>
        <th>商品ID</th>
        <th>商品名称</th>
        <th>商品描述</th>
        <th>操作</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="product in products" :key="product.productId">
        <td>
          {{ product.productId }}
        </td>
        <td>
          {{ product.name }}
        </td>
        <td>
          <div v-html="product.description"></div>
        </td>
        <td>
          <button class="look"
                  @click="$router.push({ name: 'ProductDetail', params: { productId: product.productId } })">详情
          </button>
          <button class="select" @click="$router.push({ name: 'ItemList', params: { productId: product.productId } })">
            挑选
          </button>
        </td>
      </tr>
      </tbody>
    </table>
  </div>
</template>

<style scoped>
.product-list {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
}

th, td {
  padding: 12px;
  text-align: center;
  border: 1px solid #ddd;
}

th {
  background-color: #f5f5f5;
  font-weight: 600;
}

tr:hover {
  background-color: #f9f9f9;
}

.product-item {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #eee;
  border-radius: 4px;
}
</style>